<template>
  <div class="container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>试题录入</span>
      </div>
      <el-row :gutter="15">
        <el-form ref="addQuestion" :model="formData" :rules="rules" size="medium" label-width="100px">
          <el-col :span="24">
            <el-form-item label="学科" prop="subjectID">
              <el-select v-model="formData.subjectID" placeholder="请选择学科" clearable :style="{ width: '40%' }" @change="getDirectoryBySubjects()">
                <el-option v-for="(item, index) in subjectIDOptions" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="目录" prop="catalogID">
              <el-select v-model="formData.catalogID" placeholder="请选择目录" clearable :style="{ width: '40%' }" @change="getTagsByDirectory()">
                <el-option v-for="(item, index) in catalogIDOptions" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="企业" prop="enterpriseID">
              <el-select v-model="formData.enterpriseID" placeholder="请选择企业" clearable :style="{ width: '40%' }">
                <el-option v-for="(item, index) in enterpriseIDOptions" :key="index" :label="item.company" :value="item.id" :disabled="item.disabled" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="城市" prop="province">
              <el-select ref="province" v-model="formData.province" placeholder="请选择城市" clearable :style="{ width: '100%' }" @change="cityChange">
                <el-option v-for="(item, index) in provinceOptions" :key="index" :label="item" :value="item" :disabled="item.disabled" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="0" prop="city">
              <el-select v-model="formData.city" placeholder="请选择" clearable :style="{ width: '30%' }">
                <el-option v-for="(item, index) in cityOptions" :key="index" :label="item" :value="item" :disabled="item.disabled" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="方向" prop="direction">
              <el-select v-model="formData.direction" placeholder="请选择方向" clearable :style="{ width: '40%' }">
                <el-option v-for="(item, index) in directionOptions" :key="index" :label="item" :value="item" :disabled="item.disabled" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="题型" prop="questionType">
              <el-radio-group v-model="formData.questionType" size="medium">
                <el-radio v-for="(item, index) in questionTypeOptions" :key="index" :ref="item" :label="item.value" :disabled="item.disabled" @change="QuesType(item.label)">{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="难度" prop="difficulty">
              <el-radio-group v-model="formData.difficulty" size="medium">
                <el-radio v-for="(item, index) in difficultyOptions" :key="index" :label="item.value">{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item class="local-quill-editor" label="题干" prop="question">
              <quill-editor ref="myLQuillEditor" v-model="formData.question" :options="editorOption" class="editor" />
            </el-form-item>
          </el-col>
          <!-- 单选框 -->
          <el-col v-if="radioShow" :span="24">
            <el-form-item label="选项">
              <el-radio-group v-model="isRightList[0]" size="medium" style="display:'block;" @change="isRightChange">
                <!-- v-model="item.isRight" -->
                <el-radio v-for="(item, index) in codeOptions" :key="index" :label="item.code" :disabled="item.disabled" class="block" @click="changeBtn">
                  {{ item.code }}
                  <el-input v-model="item.title" placeholder="请输入" clearable :style="{ width: '200px', margin: '10px' }" />
                  <el-upload action="#" :file-list="optionsImgfileList" style="display: inline-block" :before-upload="optionsImgBeforeUpload" list-type="picture">
                    <el-button size="small" type="primary" icon="el-icon-upload">上传图片</el-button>
                  </el-upload>
                  <!-- -->
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <!-- 单选框 -->
          <!-- 多选框 -->
          <el-col v-if="checkShow" :span="24">
            <el-form-item label="选项">
              <el-checkbox-group v-model="isRightList" size="medium" @change="isRightChange">
                <el-checkbox v-for="(item, index) in codeOptions" :key="index" v-model="item.isRight" :label="item.code" :disabled="item.disabled" class="blockB">
                  {{ item.code }}
                  <el-form-item label-width="0" prop="title" class="block position">
                    <el-input v-model="item.title" placeholder="请输入" clearable :style="{ width: '100%' }" />
                  </el-form-item>
                  <el-form-item label-width="0" class="block position-btn">
                    <el-upload :file-list="optionsImgfileList" :before-upload="optionsImgBeforeUpload" action="#">
                      <el-button size="small" type="primary" icon="el-icon-upload">上传图片</el-button>
                    </el-upload>
                  </el-form-item>
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <!-- 多选框 -->
          <el-col v-show="radioShowbtn" :span="24">
            <el-button type="primary" class="btn" small :disabled="disabled" @click="addCheckbox">增加选项与答案</el-button>
          </el-col>
          <el-col :span="24">
            <el-form-item label="解析视频" prop="videoURL">
              <el-input v-model="formData.videoURL" placeholder="请输入解析视频" clearable :style="{ width: '40%' }" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item class="local-quill-editor" label="答案解析" prop="answer">
              <quill-editor ref="myLQuillEditor" v-model="formData.answer" :options="editorOption" class="editor" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="题目备注" prop="remarks">
              <el-input v-model="formData.remarks" type="textarea" placeholder="请输入题目备注" :autosize="{ minRows: 4, maxRows: 4 }" :style="{ width: '100%' }" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="试题标签" prop="tags">
              <el-select v-model="myTags" placeholder="请选择试题标签" clearable multiple :style="{ width: '40%' }">
                <el-option v-for="(item, index) in tagsOptions" :key="index" :label="item.label" :value="item.label" :disabled="item.disabled" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item size="large">
              <el-button v-if="btn" type="primary" @click="submitForm">确认提交</el-button>
              <el-button v-else type="primary" @click="editForm">确认修改</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
    </el-card>
  </div>
</template>
<script>
import { add, detail, update } from '@/api/hmmm/questions'
import { provinces, citys } from '@/api/hmmm/citys'
import { simple } from '@/api/hmmm/subjects'
import { simple as directory } from '@/api/hmmm/directorys'
import { simple as tagsSimple } from '@/api/hmmm/tags'
import { list } from '@/api/hmmm/companys'

import { direction, questionType, difficulty } from '@/api/hmmm/constants'

import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
const toolbarOptions = [
  // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  ['bold', 'italic', 'underline', 'strike'],
  // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  [{ list: 'ordered' }, { list: 'bullet' }],
  ['blockquote'],
  // 链接、图片、视频-----['link', 'image', 'video']
  ['code-block', 'image', 'link']
]
export default {
  name: 'QuestionsNew',
  components: { quillEditor },
  props: [],
  data() {
    return {
      btn: true,
      myTags: [],
      radioShow: true, // 单选框和按钮显示或隐藏
      disabled: true, // 添家多选框按钮是否禁用
      checkShow: false, // 多选框显示
      radioShowbtn: true,
      isRightList: [],
      provinceOptions: [],
      formData: {
        id: '',
        subjectID: undefined,
        catalogID: undefined,
        enterpriseID: undefined,
        province: undefined,
        city: undefined,
        direction: undefined,
        questionType: '',
        difficulty: '',
        videoURL: undefined,
        answer: undefined,
        remarks: undefined,
        tags: 'undefined',
        options: []
      },
      codeOptions: [
        {
          code: 'A',
          value: 1,
          title: '',
          isRight: false
        },
        {
          code: 'B',
          value: 2,
          title: '',
          isRight: false
        },
        {
          code: 'C',
          value: 3,
          title: '',
          isRight: false
        },
        {
          code: 'D',
          value: 4,
          title: '',
          isRight: false
        }
      ],
      rules: {
        subjectID: [
          {
            required: true,
            message: '请选择学科',
            trigger: 'blur'
          }
        ],
        catalogID: [
          {
            required: true,
            message: '请选择目录',
            trigger: 'blur'
          }
        ],
        enterpriseID: [
          {
            required: true,
            message: '请选择企业',
            trigger: 'blur'
          }
        ],
        province: [],
        city: [
          {
            required: true,
            message: '请选择',
            trigger: 'blur'
          }
        ],
        direction: [
          {
            required: true,
            message: '请选择方向',
            trigger: 'blur'
          }
        ],
        questionType: [],
        difficulty: [],
        question: [
          {
            required: true,
            message: '请输入题干',
            trigger: 'blur'
          }
        ],
        options: [
          {
            required: true,
            message: '选项不能为空',
            trigger: 'blur'
          }
        ],
        title: [],
        videoURL: [],
        answer: [],
        remarks: [],
        tags: []
      },
      optionsImgfileList: [],
      subjectIDOptions: [],
      catalogIDOptions: [],
      enterpriseIDOptions: [],
      cityOptions: [],
      directionOptions: [],
      questionTypeOptions: [],
      difficultyOptions: [],
      tagsOptions: [],
      editorOption: {
        modules: {
          toolbar: toolbarOptions
        },
        theme: 'snow',
        placeholder: ''
        // Some Quill optiosn...
      }
    }
  },
  computed: {
    details() {
      return this.$route.query || null
    }
  },
  watch: {},
  async created() {
    this.provinceOptions = await provinces() // 省
    const { data } = await simple() // 学科
    this.subjectIDOptions = data
    const {
      data: { items }
    } = await list() // 企业
    this.enterpriseIDOptions = items
    this.directionOptions = direction // 方向
    this.questionTypeOptions = questionType // 题型
    this.difficultyOptions = difficulty // 难度
  },
  async mounted() {
    if (this.$route.query.id) {
      this.btn = false
      this.getList()
    }
  },
  methods: {
    // 编辑按钮
    async editForm() {
      await update(this.formData)
      this.$message.success('试题编辑成功')
      this.formData = this.$options.data().formData
      this.myTags = []
      this.btn = true
    },
    // 编辑
    async getList() {
      this.formData.id = this.details.id || 75
      const res = await detail(this.formData)
      this.formData = res.data

      // 处理选中状态的数据传给子组件
      this.isRightList = res.data.options.filter((item, index, arr) => item.isRight === 1).map(ele => ele.code) //
      if (this.formData.questionType === '多选') {
        this.radioShow = false
        this.checkShow = true
      }
      // 渲染目录需要重新获取一边数据
      this.myTags = res.data.tags.split(',')
      this.getDirectoryBySubjects(res.data.subjectID)
      this.getTagsByDirectory(res.data.subjectID)
    },
    // 单选
    isRightChange() {
      this.codeOptions.forEach(e => {
        e.isRight = false
        if (this.isRightList.includes(e.code)) {
          e.isRight = true
        }
      })
    },
    // 多选添加
    addCheckbox() {
      if (this.codeOptions.length === 4) {
        this.codeOptions.push({
          code: 'E',
          value: 5,
          title: '',
          isRight: false
        })
      } else if (this.codeOptions.length === 5) {
        this.codeOptions.push({
          code: 'F',
          value: 6,
          title: '',
          isRight: false
        })
      } else {
        this.$message.error('最多只能添加6条数据哦~')
      }
      this.codeOptions.push()
    },
    // 单选复选框
    QuesType(item) {
      this.codeOptions = this.$options.data().codeOptions
      this.isRightList = []
      if (item === '单选') {
        this.disabled = true
        this.radioShow = true
        this.radioShowbtn = true
        this.checkShow = false
      }
      if (item === '多选') {
        this.radioShowbtn = true
        this.disabled = false
        this.radioShow = false
        this.checkShow = true
      }
      if (item === '简答') {
        this.radioShow = false
        this.checkShow = false
        this.radioShowbtn = false
      }
    },
    // 根据学科获取目录
    async getDirectoryBySubjects(subjectID) {
      subjectID = subjectID || this.formData.subjectID
      // subjectID = this.formData.subjectID
      const data = {
        page: 1,
        pagesize: 99,
        subjectID
      }
      const { data: cataList } = await directory(data)
      this.catalogIDOptions = cataList
      return cataList
    },
    // 根据学科目录获取标签
    async getTagsByDirectory(subjectID) {
      subjectID = subjectID || this.formData.subjectID
      const data = {
        page: 1,
        pagesize: 99,
        subjectID
      }
      const { data: tagsList } = await tagsSimple(data)
      this.tagsOptions = tagsList
      // this.formData.tags = ''
      return tagsList
    },
    changeBtn() {
      this.disabled = false
    },
    async cityChange() {
      const city = this.formData.province
      this.cityOptions = await citys(city)
    },
    submitForm() {
      this.$refs.addQuestion.validate(async valid => {
        if (valid) {
          this.formData.tags = this.myTags.join('')
          this.formData.options = this.codeOptions
          await add(this.formData)
          this.$message.success('试题录入成功')
          this.formData = this.$options.data().formData
          this.myTags = []
        }

        // TODO 提交表单
      })
    },
    optionsImgBeforeUpload(file) {
      const isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      return isRightSize
    }
  }
}
</script>
<style>
.el-upload__tip {
  line-height: 1.2;
}
.block {
  display: block;
}
.btn {
  margin: 0 0 20px 100px;
}
.blockB {
  display: flex;
  position: relative;
  height: 50px;
}
.position {
  position: absolute;
  width: 200px;
  left: 40px;
  top: 0px;
  margin: 0 20px 0 5px;
}
.position-btn {
  position: absolute;
  left: 250px;
  top: 0px;
  margin: 0 200px 0 5px;
}
.editor {
  height: 250px;
  margin-bottom: 55px;
}
.box-card {
  margin: 15px 15px 20px 20px;
}
</style>
